import { h, Fragment } from "preact";
import { useEffect, useRef } from "preact/hooks";
import { Handlers, PageProps } from "$fresh/server.ts";
import HeadComponent from "../../../components/Head.tsx";
import Button from "../../../components/Button.tsx";
import { AdminState } from "../../_middleware.ts"; // Import AdminState for ctx.state type

// Handler to ensure only admins can access this page
export const handler: Handlers<null, AdminState> = {
  GET(req, ctx) {
    if (!ctx.state.isAdmin) {
      // Redirect non-admins to login or homepage
      const headers = new Headers();
      headers.set("location", "/admin/login?redirect=/admin/posts/new"); // Redirect to login, then back here
      return new Response(null, { status: 303, headers });
    }
    return ctx.render();
  },
};

export default function NewPostPage({ state }: PageProps<null, AdminState>) {
  const { isAdmin, adminNickname, adminAvatarUrl } = state;
  const editorRef = useRef<HTMLTextAreaElement>(null);
  const easyMDERef = useRef<any>(null);

  // 在组件加载后初始化 EasyMDE
  useEffect(() => {
    // 动态导入 EasyMDE
    import("https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js").then(() => {
      if (!window.EasyMDE) {
        console.error("EasyMDE library not available");
        return;
      }
      
      if (editorRef.current && !easyMDERef.current) {
        // 图片上传处理函数
        const imageUploadFunction = async (file: File, onSuccess: (url: string) => void, onError: (error: string) => void) => {
          try {
            // 创建 FormData 对象
            const formData = new FormData();
            formData.append('image', file);
            
            // 发送请求到我们的上传API
            const response = await fetch('/api/upload/image', {
              method: 'POST',
              body: formData
            });
            
            // 解析响应
            const result = await response.json();
            
            // 检查上传是否成功
            if (result.success && result.url) {
              onSuccess(result.url);
            } else {
              onError(result.error || 'Image upload failed');
            }
          } catch (error) {
            console.error('Image upload error:', error);
            onError('Image upload failed: ' + (error.message || 'Unknown error'));
          }
        };
        
        // 配置编辑器
        easyMDERef.current = new window.EasyMDE({
          element: editorRef.current,
          autofocus: true,
          spellChecker: false,
          status: ["lines", "words", "cursor"],
          placeholder: "在这里使用 Markdown 格式编写文章内容...",
          toolbar: [
            "bold", "italic", "heading", "|", 
            "quote", "unordered-list", "ordered-list", "|", 
            "link", 
            {
              name: "custom-image",
              action: function customFunction(editor) {
                // 触发默认的图片上传对话框但使用我们的上传功能
                editor.codemirror.options.imageUploadFunction(
                  editor.codemirror.options.imageUploadFunction
                );
              },
              className: "fa fa-picture-o",
              title: "插入图片"
            },
            "code", "table", "|", 
            "preview", "side-by-side", "fullscreen", "|",
            "guide"
          ],
          // 使用我们定义的上传函数
          imageUploadFunction: imageUploadFunction
        });
      }
    });

    // 在组件卸载时清理
    return () => {
      if (easyMDERef.current) {
        easyMDERef.current.toTextArea();
        easyMDERef.current = null;
      }
    };
  }, []);

  return (
    <>
      <HeadComponent title="创建新文章" description="撰写新的博客文章">
        <link rel="stylesheet" href="/styles.css" />
        <link rel="stylesheet" href="/article-styles.css" /> {/* For consistent background/header/footer */}
        
        {/* EasyMDE CSS */}
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

        <style>{`
          .CodeMirror {
            border: 1px solid #ddd;
            border-radius: 0.375rem;
            height: 400px;
          }
          .editor-toolbar {
            border: 1px solid #ddd;
            border-radius: 0.375rem 0.375rem 0 0;
          }
          .editor-statusbar {
            padding: 8px 10px;
            font-size: 12px;
            color: #777;
            text-align: right;
          }
          /* 图片上传时的加载状态 */
          .image-uploading::after {
            content: "上传中...";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
          }
        `}</style>
        
        <script dangerouslySetInnerHTML={{__html: `
          // 确保滚动效果
          document.addEventListener('DOMContentLoaded', function() {
            document.body.style.overflow = 'auto';
            document.body.style.maxHeight = 'none';
            document.body.style.height = 'auto';
          });
          
          // 定义全局 EasyMDE 类型
          declare global {
            interface Window {
              EasyMDE: any;
            }
          }
        `}} />
      </HeadComponent>

      <div class="article-container flex flex-col min-h-screen">
        {/* Header similar to article page */}
        <header class="article-header-glass sticky top-0 z-50">
          <div class="container mx-auto max-w-3xl py-3 px-4 md:px-0 flex items-center justify-between">
            <a href="/" class="flex items-center space-x-2 text-gray-600 hover:text-blue-600 transition-colors duration-200">
              {/* Back arrow SVG */}
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              <span class="text-sm font-medium">返回首页</span>
            </a>
            {isAdmin && adminNickname && (
              <div class="flex items-center gap-3">
                {adminAvatarUrl && adminAvatarUrl.trim() !== "" ? (
                  <img src={adminAvatarUrl} alt={adminNickname} class="w-7 h-7 rounded-full object-cover border border-gray-300 shadow-sm" />
                ) : (
                  <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 border border-slate-300 shadow-sm">
                    {adminNickname.charAt(0).toUpperCase()}
                  </div>
                )}
                <a href="/api/auth/logout" class="text-sm text-gray-700 font-medium hover:text-blue-700 hover:underline cursor-pointer" title="点击退出登录">
                  你好, {adminNickname}
                </a>
              </div>
            )}
            {isAdmin && !adminNickname && ( // Fallback for generic admin display
                <div class="flex items-center gap-3">
                    <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-gray-500 border border-slate-300 shadow-sm">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                        </svg>
                    </div>
                    <a href="/api/auth/logout" class="text-xs text-blue-600 hover:text-blue-800 hover:underline">退出登录</a>
                </div>
            )}
          </div>
        </header>

        <main class="flex-grow py-10 md:py-12 px-4 md:px-0 article-content animate-enter">
          <div class="container mx-auto max-w-3xl bg-white p-6 md:p-10 rounded-lg shadow-subtle poetic-card-base-styles">
            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-8 leading-tight">撰写新文章</h1>
            
            <form method="POST" action="/api/posts/create">
              <div class="mb-6">
                <label htmlFor="title" class="block text-sm font-medium text-gray-700 mb-1">标题</label>
                <input 
                  type="text" 
                  name="title" 
                  id="title" 
                  required 
                  class="input w-full text-lg px-4 py-2.5 border-gray-300 focus:border-primary-500 focus:ring-primary-500/50"
                  placeholder="文章标题"
                />
              </div>

              <div class="mb-8">
                <label htmlFor="content" class="block text-sm font-medium text-gray-700 mb-1">内容 (Markdown)</label>
                <textarea 
                  ref={editorRef}
                  name="content" 
                  id="content" 
                  required 
                  class="input w-full text-base px-4 py-2.5 border-gray-300 focus:border-primary-500 focus:ring-primary-500/50"
                  placeholder="在这里使用 Markdown 格式编写文章内容..."
                ></textarea>
                {/* EasyMDE 将替换此文本区域 */}
              </div>

              <div class="flex items-center justify-end gap-4">
                <Button type="button" variant="outline" href="/">
                  取消
                </Button>
                <Button type="submit" variant="primary">
                  发布文章
                </Button>
              </div>
            </form>
          </div>
        </main>

        {/* Footer similar to article page */}
        <footer class="article-footer-glass py-8 mt-auto">
          <div class="container mx-auto max-w-3xl px-4 md:px-0">
            <p class="text-xs text-gray-500 text-center">
              © {new Date().getFullYear()} MiniBlog. 保留所有权利。
            </p>
          </div>
        </footer>
      </div>
    </>
  );
} 